package com.gable.exhibition.util;

import com.gable.common.util.StringUtil;
import com.gable.exhibition.dao.CheckExeclDao;
import com.gable.exhibition.model.User;
import com.gable.exhibition.view.ImportExcelDeviceModel;
import com.gable.exhibition.view.ImportExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Lesson on 2018/2/23.
 */
@Component
public class CheckImportExcelDevice {

    @Autowired
    CheckExeclDao checkExeclDao;

    public static String [] properties = new String [] {
            "deviceName","deviceModel","sn","hospitalCode","manufacturerNo","maintainerNo","department","assetsNo","placeOrigin","specifications",
    "priceStr","quantityStr","attachment","upkeepCycleStr","lastUpkeepDate","installDate","acceptanceDate","purchaseDate","manufactureDate",
    "responsiblePerson","deviceStatusStr","deviceTypeStr","deviceTypeSubStr","remark"};


    private String REGNUMBER = "^[0-9]\\d*(\\.\\d{1,2})?$";

    private String REGINTEGER = "^\\+?[0-9]\\d*$";

    //private String REGDATE = "^(\\d{4})-(0\\d{1}|1[0-2])-(0\\d{1}|[12]\\d{1}|3[01])$";

    private String REGDATE = "^((((1[6-9]|[2-9]\\d)\\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\\d|3[01]))|(((1[6-9]|[2-9]\\d)\\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\\d|30))|(((1[6-9]|[2-9]\\d)\\d{2})-0?2-(0?[1-9]|1\\d|2[0-8]))|(((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$";


    //用户id作为key
    public static Map<Long,Object> resultMap = new ConcurrentHashMap<Long,Object>();



    public ImportExcelView checkImportExcelDevice(List<ImportExcelDeviceModel> list, User user){


        //给到客户端的数据集
        ImportExcelView iev = new ImportExcelView();

        //错误信息
        List<String> errorMessage = new ArrayList<String>();

        int count=0;

        Map map = new HashMap();

        if(list == null || list.size()==0){
            return null;
        }

        Map<String,Integer> snMap = new HashMap<String,Integer>();

        for(int i = 0;i < list.size();i++) {
            int row = i + 1;
            if(!StringUtil.isEmpty(list.get(i).getSn())){
                int conuts = checkExeclDao.checkDeviceSn(list.get(i).getSn());
                if(conuts > 0){
                    errorMessage.add("第" + row + "行，第" + queryProperties("sn") + "列的序列号已存在");
                    count++;
                }
                boolean bl = true;
                if(snMap.containsKey(list.get(i).getSn())){
                    errorMessage.add("第"+row+"行，第"+queryProperties("sn")+"列的序列号和"+"第"+snMap.get(list.get(i).getSn())+"行，"+"第"+queryProperties("sn")+"列的序列号相同");
                    count++;
                    bl=false;
                }

                if(bl){
                    snMap.put(list.get(i).getSn(),row);
                }
            }

            if(!StringUtil.isEmpty(list.get(i).getHospitalCode())){
               Long hospitalId = checkExeclDao.queryHospitalIdByHospitalCode(list.get(i).getHospitalCode());
                if(hospitalId == null){
                    errorMessage.add("第" + row + "行，第" + queryProperties("hospitalCode") + "列的医院不存在");
                    count++;
                }
                list.get(i).setHospitalId(hospitalId);
            }

            if(!StringUtil.isEmpty(list.get(i).getManufacturerNo())){
                Long manufacturerId = checkExeclDao.queryManufacturerIdByNo(list.get(i).getManufacturerNo());
                if(manufacturerId == null){
                    errorMessage.add("第" + row + "行，第" + queryProperties("manufacturerNo") + "列的厂商不存在");
                    count++;
                }
                list.get(i).setManufacturerId(manufacturerId);
            }

            if(!StringUtil.isEmpty(list.get(i).getMaintainerNo())){
                Long maintainerId = checkExeclDao.queryMaintainerIdByMaintainerNo(list.get(i).getMaintainerNo());
                if(maintainerId == null){
                    errorMessage.add("第" + row + "行，第" + queryProperties("maintainerNo") + "列的维修商不存在");
                    count++;
                }
                list.get(i).setMaintainerId(maintainerId);
            }


            if(!StringUtil.isEmpty(list.get(i).getPriceStr())){
                boolean bl = CheckPattern(REGNUMBER,list.get(i).getPriceStr());
                if(!bl){
                    errorMessage.add("第"+row+"行，第"+queryProperties("priceStr")+"列的单价格式不正确");
                    count++;
                }else{
                   double price = Double.parseDouble(list.get(i).getPriceStr());
                   price = price * 100;
                   list.get(i).setPrice((long)price);
                }
            }

            if(!StringUtil.isEmpty(list.get(i).getQuantityStr())){
                boolean bl = CheckPattern(REGINTEGER,list.get(i).getQuantityStr());
                if(!bl){
                    errorMessage.add("第"+row+"行，第"+queryProperties("quantityStr")+"列的数量格式不正确");
                    count++;
                }else{
                    list.get(i).setQuantity(Integer.parseInt(list.get(i).getQuantityStr()));
                }
            }

            if(!StringUtil.isEmpty(list.get(i).getUpkeepCycleStr())){
                boolean bl = CheckPattern(REGINTEGER,list.get(i).getUpkeepCycleStr());
                if(!bl){
                    errorMessage.add("第"+row+"行，第"+queryProperties("upkeepCycleStr")+"列的保养周期格式不正确");
                    count++;
                }else{
                    list.get(i).setUpkeepCycle(Integer.parseInt(list.get(i).getUpkeepCycleStr()));
                }
            }

            if(!StringUtil.isEmpty(list.get(i).getLastUpkeepDate())){
                boolean bl = CheckPattern(REGDATE,list.get(i).getLastUpkeepDate());
                if(!bl){
                    errorMessage.add("第"+row+"行，第"+queryProperties("lastUpkeepDate")+"列的上次保养时间格式不正确");
                    count++;
                }
            }

            if(!StringUtil.isEmpty(list.get(i).getInstallDate())){
                boolean bl = CheckPattern(REGDATE,list.get(i).getInstallDate());
                if(!bl){
                    errorMessage.add("第"+row+"行，第"+queryProperties("installDate")+"列的安装日期格式不正确");
                    count++;
                }
            }

            if(!StringUtil.isEmpty(list.get(i).getAcceptanceDate())){
                boolean bl = CheckPattern(REGDATE,list.get(i).getAcceptanceDate());
                if(!bl){
                    errorMessage.add("第"+row+"行，第"+queryProperties("acceptanceDate")+"列的验收日期格式不正确");
                    count++;
                }
            }

            if(!StringUtil.isEmpty(list.get(i).getPurchaseDate())){
                boolean bl = CheckPattern(REGDATE,list.get(i).getPurchaseDate());
                if(!bl){
                    errorMessage.add("第"+row+"行，第"+queryProperties("purchaseDate")+"列的购买日期格式不正确");
                    count++;
                }
            }

            if(!StringUtil.isEmpty(list.get(i).getManufactureDate())){
                boolean bl = CheckPattern(REGDATE,list.get(i).getManufactureDate());
                if(!bl){
                    errorMessage.add("第"+row+"行，第"+queryProperties("manufactureDate")+"列的出厂日期格式不正确");
                    count++;
                }
            }

            if(!StringUtil.isEmpty(list.get(i).getDeviceStatusStr())){
                Long id  = checkExeclDao.checkDeviceStatus(list.get(i).getDeviceStatusStr());
                if(id == null){
                    errorMessage.add("第"+row+"行，第"+queryProperties("deviceStatusStr")+"列的设备状态不存在");
                    count++;
                }else{
                    list.get(i).setDeviceStatus(id);
                }
            }

            Long typeId = null;
            if(!StringUtil.isEmpty(list.get(i).getDeviceTypeStr())){
                typeId = checkExeclDao.checkDeviceType(list.get(i).getDeviceTypeStr());
                if(typeId == null){
                    errorMessage.add("第"+row+"行，第"+queryProperties("deviceTypeStr")+"列的68分类一级不存在");
                    count++;
                }else{
                    list.get(i).setDeviceTypeId(typeId);
                }
            }

            if(!StringUtil.isEmpty(list.get(i).getDeviceTypeSubStr())){
                Long id = checkExeclDao.checkDeviceTypeSub(list.get(i).getDeviceTypeSubStr());
                if(id == null){
                    errorMessage.add("第"+row+"行，第"+queryProperties("deviceTypeSubStr")+"列的68分类二级不存在");
                    count++;
                }else{
                    if(typeId != null){
                        Map maps = new HashMap();
                        maps.put("id",id);
                        maps.put("parentId",typeId);
                        int result = checkExeclDao.checkDeviceTypeSubParentId(maps);
                        if(result == 0){
                            errorMessage.add("第"+row+"行，第"+queryProperties("deviceTypeStr")+"列的68分类一级和第"+row+"行，第"+queryProperties("deviceTypeSubStr")+"列的68分类二级关系错误");
                            count++;
                        }else{
                            list.get(i).setDeviceTypeSubId(id);
                        }
                    }else{
                        list.get(i).setDeviceTypeSubId(id);
                    }
                }
            }
        }

        if(count == 0){
            iev.setBool(true);
        }else{
            iev.setBool(false);
        }

        iev.setErrorMessage(errorMessage);
        return iev;
    }



    //获取Properties数组字符串的下标
    public int queryProperties(String str){
        if(str == null || str.equals("")){
            return 0;
        }
        for(int i = 0;i<properties.length;i++){
            if(properties[i].equals(str)){
                int index = i+2;
                return index;
            }
        }
        return 0;
    }

    //正则表达式
    public boolean  CheckPattern(String reg,String str){
        str = str .replaceAll("/","-");
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(str);
        boolean bl = matcher.matches();
        return bl;
    }

    //根据Map中的key删除map中的元素
    public static synchronized void removeMap (Map map,Long delKey){
        if(map == null || map.size()==0){
            return;
        }
        Iterator iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            Long key = Long.parseLong(iterator.next().toString());
            if (key.longValue() == delKey.longValue()) {
                map.remove(key);
                break;
            }
        }
    }
}
